<script lang="ts">
  import { drawStore } from "../store.svelte";
  import { listen } from "@tauri-apps/api/event";
  import type { AllNotice } from "$lib/api/notice_type";
  import { chatStore } from "./store.svelte";
  import { MessageCircleMore } from "lucide-svelte";
  import ChatModal from "./ChatModal.svelte";

  $effect(() => {
    if (
      drawStore.boardInfo != null &&
      drawStore.drawId != ""
    ) {
      chatStore.init(
        drawStore.boardInfo?.board_id ?? "",
        drawStore.drawId,
      );
    }
  });

  $effect(() => {
    const unListen = listen<AllNotice>("notice", (ev) => {
      const payload = ev.payload;
      if (payload.BoardNotice != undefined) {
        chatStore.processBoardNotice(payload.BoardNotice);
      }
    });
    return () => {
      unListen.then((fn) => fn());
    };
  });
</script>

<div
  role="none"
  class="bg-surface-200-800 p-4 rounded-[10px] relative inline-block cursor-pointer"
  onclick={() => (chatStore.showChat = true)}
>
  {#if chatStore.unreadCount > 0}
    <span
      class="badge-icon preset-filled-primary-500 absolute right-0 top-0 z-11"
      >{chatStore.unreadCount}</span
    >
  {/if}
  <MessageCircleMore />
</div>

<div class="absolute -left-[10000px]">
  {#if chatStore.showChat}
    <ChatModal />
  {/if}
</div>
